import { core_viewmodel } from '../../core/viewModel/core_viewmodel';
import { core_model } from '../../core/model/core_model';

/**
 * 示例ViewModel实现
 * 展示如何使用ViewModel基类
 */
export class example_viewmodel extends core_viewmodel {
    // 用户信息
    private _userName: string = '';
    private _userLevel: number = 1;
    private _userScore: number = 0;
    
    // 游戏状态
    private _isPlaying: boolean = false;
    private _gameTime: number = 0;
    
    // UI状态
    private _isLoading: boolean = false;
    private _errorMessage: string = '';
    
    /**
     * 初始化响应式数据
     */
    protected initializeData(): void {
        // 用户数据
        this.setData('userName', '');
        this.setData('userLevel', 1);
        this.setData('userScore', 0);
        
        // 游戏状态
        this.setData('isPlaying', false);
        this.setData('gameTime', 0);
        
        // UI状态
        this.setData('isLoading', false);
        this.setData('errorMessage', '');
    }
    
    /**
     * 初始化计算属性
     */
    protected initializeComputed(): void {
        // 用户等级显示文本
        this.addComputed('userLevelText', () => {
            const level = this.getData<number>('userLevel');
            return `等级 ${level}`;
        });
        
        // 用户分数显示文本
        this.addComputed('userScoreText', () => {
            const score = this.getData<number>('userScore');
            return `分数: ${score}`;
        });
        
        // 游戏状态显示文本
        this.addComputed('gameStatusText', () => {
            const isPlaying = this.getData<boolean>('isPlaying');
            return isPlaying ? '游戏中...' : '未开始';
        });
        
        // 游戏时间显示文本
        this.addComputed('gameTimeText', () => {
            const time = this.getData<number>('gameTime');
            const minutes = Math.floor(time / 60);
            const seconds = time % 60;
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        });
        
        // 是否可以开始游戏
        this.addComputed('canStartGame', () => {
            const isLoading = this.getData<boolean>('isLoading');
            const isPlaying = this.getData<boolean>('isPlaying');
            return !isLoading && !isPlaying;
        });
        
        // 是否可以暂停游戏
        this.addComputed('canPauseGame', () => {
            const isLoading = this.getData<boolean>('isLoading');
            const isPlaying = this.getData<boolean>('isPlaying');
            return !isLoading && isPlaying;
        });
    }
    
    /**
     * 初始化命令
     */
    protected initializeCommands(): void {
        // 开始游戏命令
        this.addCommand('startGame', () => {
            if (this.getComputed<boolean>('canStartGame')) {
                this.setData('isPlaying', true);
                this.setData('gameTime', 0);
                this.setData('errorMessage', '');
                console.log('游戏开始');
            }
        });
        
        // 暂停游戏命令
        this.addCommand('pauseGame', () => {
            if (this.getComputed<boolean>('canPauseGame')) {
                this.setData('isPlaying', false);
                console.log('游戏暂停');
            }
        });
        
        // 结束游戏命令
        this.addCommand('endGame', () => {
            this.setData('isPlaying', false);
            console.log('游戏结束');
        });
        
        // 增加分数命令
        this.addCommand('addScore', (points: number = 10) => {
            const currentScore = this.getData<number>('userScore');
            this.setData('userScore', currentScore + points);
            
            // 检查是否升级
            const newScore = this.getData<number>('userScore');
            const currentLevel = this.getData<number>('userLevel');
            const requiredScore = currentLevel * 100;
            
            if (newScore >= requiredScore) {
                this.setData('userLevel', currentLevel + 1);
                console.log(`升级到等级 ${currentLevel + 1}`);
            }
        });
        
        // 设置用户名命令
        this.addCommand('setUserName', (name: string) => {
            if (name && name.trim().length > 0) {
                this.setData('userName', name.trim());
                this.setData('errorMessage', '');
            } else {
                this.setData('errorMessage', '用户名不能为空');
            }
        });
        
        // 重置游戏命令
        this.addCommand('resetGame', () => {
            this.setData('userScore', 0);
            this.setData('userLevel', 1);
            this.setData('gameTime', 0);
            this.setData('isPlaying', false);
            this.setData('errorMessage', '');
            console.log('游戏重置');
        });
        
        // 加载数据命令
        this.addCommand('loadData', async () => {
            this.setData('isLoading', true);
            this.setData('errorMessage', '');
            
            try {
                // 模拟异步加载
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                // 从Model加载数据
                const model = this.getModel();
                if (model) {
                    const userName = model.getData<string>('userName');
                    const userLevel = model.getData<number>('userLevel');
                    const userScore = model.getData<number>('userScore');
                    
                    this.setData('userName', userName || '');
                    this.setData('userLevel', userLevel || 1);
                    this.setData('userScore', userScore || 0);
                }
                
                console.log('数据加载完成');
            } catch (error) {
                this.setData('errorMessage', '数据加载失败');
                console.error('数据加载失败:', error);
            } finally {
                this.setData('isLoading', false);
            }
        });
        
        // 保存数据命令
        this.addCommand('saveData', async () => {
            this.setData('isLoading', true);
            this.setData('errorMessage', '');
            
            try {
                // 模拟异步保存
                await new Promise(resolve => setTimeout(resolve, 500));
                
                // 保存到Model
                const model = this.getModel();
                if (model) {
                    model.setDataBatch({
                        userName: this.getData<string>('userName'),
                        userLevel: this.getData<number>('userLevel'),
                        userScore: this.getData<number>('userScore')
                    });
                }
                
                console.log('数据保存完成');
            } catch (error) {
                this.setData('errorMessage', '数据保存失败');
                console.error('数据保存失败:', error);
            } finally {
                this.setData('isLoading', false);
            }
        });
    }
    
    /**
     * 初始化完成后的回调
     */
    protected onInitialize(): void {
        // 设置游戏时间更新
        this.addEffect(() => {
            if (this.getData<boolean>('isPlaying')) {
                const interval = setInterval(() => {
                    const currentTime = this.getData<number>('gameTime');
                    this.setData('gameTime', currentTime + 1);
                }, 1000);
                
                // 清理定时器
                return () => clearInterval(interval);
            }
        });
        
        // 监听Model数据变化
        const model = this.getModel();
        if (model) {
            model.addDataListener('userName', (newValue: string) => {
                this.setData('userName', newValue);
            });
            
            model.addDataListener('userLevel', (newValue: number) => {
                this.setData('userLevel', newValue);
            });
            
            model.addDataListener('userScore', (newValue: number) => {
                this.setData('userScore', newValue);
            });
        }
    }
    
    /**
     * Model变化时的回调
     */
    protected onModelChanged(): void {
        // 重新设置Model数据监听
        this.onInitialize();
    }
    
    /**
     * 销毁前的回调
     */
    protected onDestroy(): void {
        // 清理资源
        console.log('ExampleViewModel销毁');
    }
    
    // 便捷方法
    public getUserName(): string {
        return this.getData<string>('userName');
    }
    
    public getUserLevel(): number {
        return this.getData<number>('userLevel');
    }
    
    public getUserScore(): number {
        return this.getData<number>('userScore');
    }
    
    public isPlaying(): boolean {
        return this.getData<boolean>('isPlaying');
    }
    
    public isLoading(): boolean {
        return this.getData<boolean>('isLoading');
    }
    
    public getErrorMessage(): string {
        return this.getData<string>('errorMessage');
    }
}
